library(dplyr)
library(modelsummary)
library(kableExtra)
library(stringr)
library(fixest)
library(stargazer)
library(gridExtra)
library(flextable)

survey_long <- readRDS("data/df_long.rds")

survey_long <- survey_long %>% filter(d_affiliated == 1 & d_ownparty == 0)
survey_long <- survey_long %>% 
  group_by(meta_UUID) %>%
  mutate(N_ind = n(), 
         weights = meta_Weight / N_ind,
         weights_manual = manual_weights2 / N_ind) 


sd(survey_long$feeling_toward)

########### Regression analyses

m1 <- feols(close_num ~ feeling_toward, survey_long,
            cluster = "dem_country_code", weights = survey_long$weights)
m2 <- feols(close_num ~ feeling_toward | dem_country_code, survey_long,
            weights = survey_long$weights)
m3 <- feols(close_num ~ feeling_toward | meta_UUID, survey_long %>% filter(dem_country_code != "US"), 
            weights = survey_long$weights[survey_long$dem_country_code != "US"])

options("modelsummary_format_numeric_latex" = "plain")
models <- list("(1)" = m1, "(2)" = m2, "(3)" = m3)
tab <- modelsummary(models, output = 'html', stars = TRUE,
                    coef_rename = c("feeling_toward" = "Feeling", 
                                    "dem_country_code" = "Country-FE", 
                                    "meta_UUID" = "Individual-FE"),
                    coef_omit = c("(Intercept)"),
                    gof_omit = "AIC|BIC|Log|Pseudo|Adj|Within|Std.Errors",
                    statistic = "p.value") %>%
  add_header_above(c(" " = 1, "DV: Social distance (1-7)"= 3), line = T, italic = F)

kableExtra::save_kable(tab, file = "tables/Table1.html")

tab <- modelsummary(models, output = 'output/fe_models.md', stars = TRUE,
                    coef_rename = c("feeling_toward" = "Feeling", 
                                    "dem_country_code" = "Country-FE", 
                                    "meta_UUID" = "Individual-FE"),
                    coef_omit = c("(Intercept)"),
                    gof_omit = "AIC|BIC|Log|Pseudo|Adj|Within|Std.Errors",
                    statistic = "p.value")